package com.jack.uikit.dialog

import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.jack.uikit.R
import com.jack.uikit.expand.drawable
import com.jack.uikit.expand.shapeDrawable

/**
 * dialog
 *
 * @author Jack 2021-05-01 19:40
 */
class DialogBuilder(private val activity: AppCompatActivity) {
    private var mContentView: View? = null
    var onCancelListener: (() -> Unit)? = null
    var onConfirmListener: (() -> Unit)? = null
    var onViewCreated: ((contentView: View) -> Unit)? = null

    fun <V : View> getView(id: Int): V? {
        return mContentView?.findViewById(id)
    }

    fun build(): Dialog {
        val dialog = Dialog(activity)
        var tvConfirm: TextView? = null
        var tvCancel: TextView? = null
        if (mContentView == null) {
            mContentView = LayoutInflater.from(activity).inflate(R.layout.dialog_common, null)
            mContentView?.findViewById<View>(R.id.container)?.drawable = shapeDrawable {
                solid = Color.WHITE
                radius = 10f
            }
            tvCancel = mContentView?.findViewById(R.id.tvCancel)
            tvConfirm = mContentView?.findViewById(R.id.tvConfirm)
        }
        mContentView?.apply {
            dialog.setContentView(this)
            onViewCreated?.invoke(this)
        }
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        tvCancel?.apply {
            setOnClickListener {
                dialog.dismiss()
                onCancelListener?.invoke()
            }
        }
        tvConfirm?.apply {
            setOnClickListener {
                dialog.dismiss()
                onConfirmListener?.invoke()
            }
        }
        return dialog
    }
}